<?php

namespace app\common\system\logic;

use app\common\BaseLogic;
use app\common\system\model\UserDepartment;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class UserLogic extends BaseLogic
{
    public function getUser($id, $fields = "*")
    {
        $cacheName = "user:{$id}";
        if ($fields == '*') {
            $data = $this->redis->hGetAll($cacheName);
        } else {
            $data = $this->redis->hMGet($cacheName, $fields);
        }

        if (empty_hGet($data)) {
            $fields = "id,nickname,realname,mobile,work_wechat,user_type,status,dingding,avatar";
            $where['id'] = $id;
            $model = new \app\common\system\model\User();
            $row = $model->where($where)->field($fields)->find();
            if (!empty($row)) {
                $data = $row->getData();
                $this->redis->hMSet($cacheName, $data);
                if ($fields != '*') {
                    $data = array_search_keys($data, $fields);
                }
            } else {
                $data = [];
            }
        }

        return $data;
    }

    /**
     * 获取用户的门店权限
     * @param $userId
     * @return array
     */
    public function getStoreAuth($userId): array
    {
        $model = new \app\common\system\model\UserConfig();

        try {
            $row = $model->where('id', $userId)->find();
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return [];
        }

        return $row['store'];
    }

    public function getDptUserIds($userId) {
        $logic = new UserDepartmentLogic();
        $dptIds = $logic->getUserDepartment($userId);

        $model = new UserDepartment();
        return $model->where('department_id', 'in', $dptIds)->column('user_id');
    }

    // 获取同部门下指定的角色
    public function getDptRoleUser($userId, $roleId)
    {
        $userDptLogic = new UserDepartmentLogic();
        $dptIds = $userDptLogic->getUserDepartment($userId);
        if (empty($dptIds)) return [];

        $model = new UserDepartment();
        return $model->where('department_id', 'in', $dptIds)
            ->whereIn('user_id', function ($query) use ($roleId) {
                $query->table('tk_system_user_role')->where('role_id', $roleId)->field('user_id');
            })->find();
    }

    public function checkUser($id)
    {
        $user = $this->getUser($id);

        if (empty($user['id'])) {
            throw new Exception("该员工信息不存在", 10001);
        } else if ($user['status'] == 0) {
            throw new Exception("该员工已离职", 10002);
        }

        return $user;
    }

    public function resetUserCache($id)
    {
        $cacheName = "user:{$id}";
        $this->redis->del($cacheName);
        $this->getUser($id);
    }
}